/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.diplomka.servicelayer.gamelogic.resolver;

import cz.muni.fi.diplomka.servicelayer.dto.BuildingInProgress;
import cz.muni.fi.diplomka.servicelayer.dto.Message;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.CityBuildingManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.CityManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.MessageManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.CityBuildingManagerImpl;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.CityManagerImpl;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.MessageManagerImpl;
import java.sql.Timestamp;

/**
 * Class used for checking if Building has been finished
 *
 * @author Jakub Kutil
 */
public class BuildingResolver {

    private static CityBuildingManager cityBuildingManager = new CityBuildingManagerImpl();
    private static CityManager cityManager = new CityManagerImpl();
    private static MessageManager messageManager = new MessageManagerImpl();

    public static void main(String[] args) throws InterruptedException {
        while (true) {
            for (BuildingInProgress buildingInProgress : cityBuildingManager.getAllBuildingInProgress()) {
                Timestamp now = new Timestamp(System.currentTimeMillis());
                if (buildingInProgress.getTimeOfFinish().before(now)) {
                    cityBuildingManager.upgradeBuilding(buildingInProgress.getCityId(), buildingInProgress.getCoordinates());

                    Message message = new Message();
                    message.setIdFrom(new Long(1));
                    message.setIdTo(cityManager.getOwnerOfCity(buildingInProgress.getCityId()).getId());
                    message.setSubject("Finished building");
                    message.setBody("Our builders have finished building " + buildingInProgress.getName()
                            + " at [" + buildingInProgress.getCoordinates().getX_coordinate()
                            + "," + buildingInProgress.getCoordinates().getY_coordinate() + "] in city "
                            + cityManager.getCityById(buildingInProgress.getCityId()).getName() + ".");
                    message.setTime(now);
                    message.setUnread(true);

                    messageManager.addMessage(message);
                }
            }
            Thread.sleep(1000);
        }
    }

    public void resolveBuilding(BuildingInProgress buildingInProgress) {
        if (buildingInProgress == null) {
            throw new IllegalArgumentException("Building In Progress can not be null.");
        }
        cityBuildingManager.upgradeBuilding(buildingInProgress.getCityId(), buildingInProgress.getCoordinates());
    }
}
